<template>
  <div class="home">
    <div class="talk_con">
        <div class="talk_show" id="words" ref="talk_show">
            <!-- <div class="atalk"><span>A说：吃饭了吗？</span></div>
            <div class="btalk"><span>B说：还没呢，你呢？</span></div> -->
            <div 
              :class="item.boxClass" 
              v-for="item in list" 
              :key="item.id"
            ><span>{{ item.name }}说：{{ item.msg }}</span></div>
        </div>
        <div class="talk_input">
            <div class="whotalk" id="who">
              {{ username }}
            </div>
            <input type="text" class="talk_word" id="talkwords" v-model="msg" @keyup.enter="hdClick">
            <input type="button" value="发送" class="talk_sub" id="talksub" @click="hdClick">
        </div>
    </div>
  </div>
</template>

<script>
const ws = new WebSocket('ws://192.168.3.10:3000')

export default {
  data () {
    return {
      username: '',
      key: '', // 以时间戳缓存不同名字
      msg: '',
      list: [],
      boxClass: true, // false 绿色(别人), true 蓝色(自己)
      isThrottle: false, // 节流开关
      scrollNum: 0, // 自动滚动的变量

    }
  },
  mounted(){
    this.key = localStorage.getItem('key')
    this.username = localStorage.getItem(`${this.key}`)
    // if(!this.username){
    //   alert('请先登录')
    //   this.$router.push('/login')
    // }

    ws.addEventListener('open', this.hdOpen.bind(this))
    ws.addEventListener('error', this.hdError.bind(this))
    ws.addEventListener('close', this.hdClose.bind(this))
    ws.addEventListener('message', this.hdMessage.bind(this))
  },
  methods: {
    // 点击发送
    hdClick(){
      if(this.isThrottle) return
      if(!this.msg.trim()) return

      ws.send(JSON.stringify({
        id: new Date().toLocaleString(),
        name: this.username,
        time: new Date().getTime(),
        msg: this.msg,
        boxClass: 'atalk'
      }))

      this.msg = ''

      // 节流
      this.isThrottle = true
      setTimeout(()=>{
        this.isThrottle = false
      }, 1000)
    },

    hdOpen(e){
      console.log('WebSocket open', e);
    },

    hdError(e){
      console.log('WebSocket error', e);
    },

    hdClose(e){
      console.log('WebSocket close', e);
    },

    hdMessage(e){
      const reader = new FileReader()
      reader.readAsText(e.data)
      reader.addEventListener('load', ()=>{
        let item = JSON.parse(reader.result)

        // 自己发的
        if(this.username === item.name){
          // 自己发的是蓝色框 // ? 颜色框存进数组(存名字 相同取数组中颜色响应给当前条数据)
          item.boxClass = 'btalk'
        }else{
          // 别人发的是绿色框
          item.boxClass = 'atalk'
        }

        this.list.push(item)
      })
      console.log(this.list);
    },
  },
  watch: {
    list: {
      handler(newV, oldV){
        this.$nextTick(()=>{
          // 自动滚动到底部 talk_show
          let cHeight = this.$refs.talk_show.clientHeight // 可视高度
          let sHeight = this.$refs.talk_show.scrollHeight // 可视高+滚动高
          let diff = sHeight - cHeight

          // 需要自动滚到底部
          if(diff > 0){
            let t = setInterval(()=>{
              this.$refs.talk_show.scrollTo(0, this.scrollNum)
              this.scrollNum += 1
              if(this.scrollNum >= diff) clearInterval(t)
            }, 10)
          }
        })
      }
    }
  }
}
</script>
 
<style lang = "less" scoped>
*{
  padding: 0;
  margin: 0;
  list-style: none;
}
  .home{
    .talk_con{
            width:600px;
            height:500px;
            border:1px solid #666;
            margin:50px auto 0;
            background:#f9f9f9;
        }
        .talk_show{
            width:580px;
            height:420px;
            border:1px solid #666;
            background:#fff;
            margin:10px auto 0;
            overflow:auto;
        }
        .talk_input{
            width:580px;
            margin:10px auto 0;
        }
        .whotalk{
            width:80px;
            height:30px;
            float:left;
            outline:none;
            border: 1px solid #000;
            box-sizing: border-box;
            text-align: center;
            line-height: 30px;
        }
        .talk_word{
            width:420px;
            height:26px;
            padding:0px;
            float:left;
            margin-left:10px;
            outline:none;
            text-indent:10px;
        }        
        .talk_sub{
            width:56px;
            height:30px;
            float:left;
            margin-left:10px;
        }
        .atalk{
           margin:10px; 
        }
        .atalk span{
            display:inline-block;
            background:green;
            border-radius:10px;
            color:#fff;
            padding:5px 10px;
        }
        .btalk{
            margin:10px;
            text-align:right;
        }
        .btalk span{
            display:inline-block;
            background:blue;
            border-radius:10px;
            color:#fff;
            padding:5px 10px;
        }
  }
</style>